/*
 * GuitarPanel.java
 *
 * Created on September 14, 2005, 1:02 PM
 */
package com.bff.slimserver.musicjukebox.ui;

import com.bff.slimserver.music.exceptions.PlaylistException;
import com.bff.slimserver.musicjukebox.lib.JukeboxProperties;
import com.bff.slimserver.musicjukebox.lib.actions.OpenTabAction;
import com.bff.slimserver.musicjukebox.lib.events.PlayerChosenEvent;
import com.bff.slimserver.musicjukebox.lib.events.PlayerChosenListener;
import com.bff.bjj.ui.component.BJJPanel;
import com.bff.bjj.ui.component.BJJButton;
import com.bff.bjj.utils.Utils;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Action;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.bff.slimserver.SlimPlayer;
import org.bff.slimserver.SlimPlaylist;
import org.bff.slimserver.events.PlayerChangeEvent;
import org.bff.slimserver.events.PlayerChangeListener;
import org.bff.slimserver.events.PlaylistChangeEvent;
import org.bff.slimserver.events.PlaylistChangeListener;
import org.bff.slimserver.exception.SlimConnectionException;
import org.bff.slimserver.exception.SlimException;
import org.bff.slimserver.musicobjects.SlimPlaylistItem;

/**
 *
 * @author  bill
 */
public class GuitarPanel
        extends BJJPanel
        implements PlayerChosenListener,
        PlayerChangeListener,
        PlaylistChangeListener {

    private SlimPlayer player;
    private SlimPlaylist playlist;
    private File fileToShow;
    private Action openFileAction;
    private JTextArea tablatureTextArea;
    private boolean timeSliderStartPaused = false;
    private boolean timeSliderEndPaused = false;
    private boolean looping = false;
    private int startTime;
    private int endTime;
    private TrackThread trackThread;
    private int time;

    /** Creates new form GuitarPanel */
    public GuitarPanel() {
        JukeboxProperties jp = JukeboxProperties.getInstance();

        try {
            this.player = jp.getPlayer();
            this.playlist = jp.getPlaylist();
        } catch (PlaylistException ex) {
            Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
        }

        this.tablatureTextArea = new JTextArea();

        this.openFileAction = new OpenTabAction(this, tablatureTextArea);

        initComponents();

        JukeboxProperties.getInstance().addPlayerChosenListener(this);
        startTimeSlider.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent event) {
                startTimeLabel.setText(Utils.formatTime(startTimeSlider.getValue()));
                verifyEndTime();
            }
        });

        endTimeSlider.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent event) {
                endTimeLabel.setText(Utils.formatTime(endTimeSlider.getValue()));
                verifyEndTime();
            }
        });
        try {
            setSongInfo(getPlaylist().getCurrentItem());
        } catch (SlimException ex) {
            Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
        }

        jp.getSlimMonitor().addPlaylistChangeListener(this);
        jp.getSlimMonitor().addPlayerChangeListener(this);
        jp.addPlayerChosenListener(this);

        try {
            if (getPlayer().isPlaying()) {
                startTrackThread();
            }
        } catch (SlimException ex) {
            Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void startTrackThread() {
        if (trackThread != null) {
            trackThread.setStopped(true);
        }
        trackThread = new TrackThread();
        new Thread(trackThread).start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new BJJPanel();
        endTimeLabel = new javax.swing.JLabel();
        startTimeLabel = new javax.swing.JLabel();
        startTimeSlider = new javax.swing.JSlider();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        btnPauseStart = new BJJButton();
        btnPauseEnd = new BJJButton();
        btnLoop = new BJJButton();
        tfDelay = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        lblCountDown = new javax.swing.JLabel();
        endTimeSlider = new javax.swing.JSlider();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabTextArea = tablatureTextArea;
        jPanel2 = new BJJPanel();
        btnOpenFile = new BJJButton(openFileAction);

        setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.GridBagLayout());

        endTimeLabel.setText("0:00");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 1, 5, 5);
        jPanel1.add(endTimeLabel, gridBagConstraints);

        startTimeLabel.setText("0:00");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 1, 5, 5);
        jPanel1.add(startTimeLabel, gridBagConstraints);

        startTimeSlider.setValue(0);
        startTimeSlider.setMinimumSize(new java.awt.Dimension(400, 25));
        startTimeSlider.setPreferredSize(new java.awt.Dimension(400, 25));
        startTimeSlider.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                startSliderMouseReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(startTimeSlider, gridBagConstraints);

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel5.setText("Start:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(jLabel5, gridBagConstraints);

        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jLabel6.setText("End:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(jLabel6, gridBagConstraints);

        btnPauseStart.setText("Pause");
        btnPauseStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPauseStartActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(btnPauseStart, gridBagConstraints);

        btnPauseEnd.setText("Pause");
        btnPauseEnd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPauseEndActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(btnPauseEnd, gridBagConstraints);

        btnLoop.setText(" Loop ");
        btnLoop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoopActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(btnLoop, gridBagConstraints);

        tfDelay.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        tfDelay.setText("5");
        tfDelay.setPreferredSize(new java.awt.Dimension(20, 22));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        jPanel1.add(tfDelay, gridBagConstraints);

        jLabel1.setText("Delay:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        jPanel1.add(jLabel1, gridBagConstraints);

        lblCountDown.setFont(new java.awt.Font("Tahoma", 1, 48));
        lblCountDown.setText("5");
        lblCountDown.setMaximumSize(new java.awt.Dimension(67, 58));
        lblCountDown.setMinimumSize(new java.awt.Dimension(67, 58));
        lblCountDown.setPreferredSize(new java.awt.Dimension(67, 58));
        lblCountDown.setVisible(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        jPanel1.add(lblCountDown, gridBagConstraints);

        endTimeSlider.setValue(0);
        endTimeSlider.setMinimumSize(new java.awt.Dimension(400, 25));
        endTimeSlider.setPreferredSize(new java.awt.Dimension(400, 25));
        endTimeSlider.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                endTimeSliderstartSliderMouseReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(endTimeSlider, gridBagConstraints);

        add(jPanel1, java.awt.BorderLayout.NORTH);

        tabTextArea.setColumns(2);
        tabTextArea.setFont(new java.awt.Font("Courier", 0, 12));
        jScrollPane1.setViewportView(tabTextArea);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel2.add(btnOpenFile);

        add(jPanel2, java.awt.BorderLayout.SOUTH);
    }// </editor-fold>//GEN-END:initComponents

    private void endSliderMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_endSliderMouseReleased
        if (endTimeSlider.getValue() > startTimeSlider.getValue()) {
            setTimeSliderEndPaused(true);
            btnPauseEnd.setText("Synch");
        }
    }//GEN-LAST:event_endSliderMouseReleased

    private void startSliderMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_startSliderMouseReleased
        setTimeSliderStartPaused(true);
        btnPauseStart.setText("Synch");
    }//GEN-LAST:event_startSliderMouseReleased

    private void btnLoopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoopActionPerformed
        if (endTimeSlider.getValue() > startTimeSlider.getValue()) {
            if (isLooping()) {
                setLooping(false);
                btnLoop.setText(" Loop ");
            } else {
                setStartTime(startTimeSlider.getValue());
                setEndTime(endTimeSlider.getValue());
                setLooping(true);
                new Thread(new LoopingThread()).start();
                btnLoop.setText("UnLoop");
            }
        }
    }//GEN-LAST:event_btnLoopActionPerformed

    private void btnPauseEndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPauseEndActionPerformed
        if (isTimeSliderEndPaused()) {
            setTimeSliderEndPaused(false);
            btnPauseEnd.setText("Pause");
        } else {
            setTimeSliderEndPaused(true);
            btnPauseEnd.setText("Synch");
        }
    }//GEN-LAST:event_btnPauseEndActionPerformed

    private void btnPauseStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPauseStartActionPerformed
        if (isTimeSliderStartPaused()) {
            setTimeSliderStartPaused(false);
        } else {
            setTimeSliderStartPaused(true);
        }
    }//GEN-LAST:event_btnPauseStartActionPerformed

    private void endTimeSliderstartSliderMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_endTimeSliderstartSliderMouseReleased
        if (endTimeSlider.getValue() > startTimeSlider.getValue()) {
            setTimeSliderEndPaused(true);
            btnPauseEnd.setText("Synch");
        }
    }//GEN-LAST:event_endTimeSliderstartSliderMouseReleased
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLoop;
    private javax.swing.JButton btnOpenFile;
    private javax.swing.JButton btnPauseEnd;
    private javax.swing.JButton btnPauseStart;
    private javax.swing.JLabel endTimeLabel;
    private javax.swing.JSlider endTimeSlider;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCountDown;
    private javax.swing.JLabel startTimeLabel;
    private javax.swing.JSlider startTimeSlider;
    private javax.swing.JTextArea tabTextArea;
    private javax.swing.JTextField tfDelay;
    // End of variables declaration//GEN-END:variables

    public void setElapsedTrackTime(long time) {
        if (!isTimeSliderStartPaused()) {
            startTimeSlider.setValue((int) time);
        }
        if (!isTimeSliderEndPaused()) {
            endTimeSlider.setValue((int) time);
        }
    }

    public boolean isTimeSliderStartPaused() {
        return timeSliderStartPaused;
    }

    public void setTimeSliderStartPaused(boolean timeSliderStartPaused) {
        this.timeSliderStartPaused = timeSliderStartPaused;
        if (timeSliderStartPaused) {
            btnPauseStart.setText("Synch");
        } else {
            btnPauseStart.setText("Pause");
        }
    }

    public boolean isTimeSliderEndPaused() {
        return timeSliderEndPaused;
    }

    public void setTimeSliderEndPaused(boolean timeSliderEndPaused) {
        this.timeSliderEndPaused = timeSliderEndPaused;
        if (timeSliderEndPaused) {
            btnPauseEnd.setText("Synch");
        } else {
            btnPauseEnd.setText("Pause");
        }
    }

    private void setSongInfo(SlimPlaylistItem song) {
        if (song != null) {
            startTimeSlider.setMaximum((int) song.getLength());
            endTimeSlider.setMaximum((int) song.getLength());
        }
    }

    private void verifyEndTime() {
        if (endTimeSlider.getValue() < startTimeSlider.getValue()) {
            endTimeSlider.setValue(startTimeSlider.getValue());
            setTimeSliderEndPaused(false);
        }
    }

    public boolean isLooping() {
        return looping;
    }

    public void setLooping(boolean looping) {
        this.looping = looping;
    }

    @Override
    public void playerChosen(PlayerChosenEvent event) {
        this.setPlayer(event.getNewPlayer());
    }

    @Override
    public void playerChanged(PlayerChangeEvent event) {
        switch (event.getId()) {
            case (PlayerChangeEvent.PLAYER_STOPPED):
                setElapsedTrackTime(0);

                if (trackThread != null) {
                    trackThread.setStopped(true);
                }
                break;
            case (PlayerChangeEvent.PLAYER_STARTED):
                try {
                    if (getPlayer().isPlaying()) {
                        startTrackThread();
                    }
                    setSongInfo(getPlaylist().getCurrentItem());
                } catch (SlimException ex) {
                    Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            case (PlayerChangeEvent.PLAYER_PAUSED):
                //statusLabel.setText("Paused");
                break;
            case (PlayerChangeEvent.PLAYER_UNPAUSED):
                //statusLabel.setText("Playing");
                break;
            default:
                break;
        }
    }

    @Override
    public void playlistChanged(PlaylistChangeEvent event) {
        switch (event.getId()) {
            case (PlaylistChangeEvent.ITEM_CHANGED):
                try {
                    setSongInfo(getPlaylist().getCurrentItem());
                } catch (SlimException ex) {
                    Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;

            default:
                break;
        }
    }
    private boolean countDownThreadRunning;

    /**
     * @return the player
     */
    public SlimPlayer getPlayer() {
        return player;
    }

    /**
     * @param player the player to set
     */
    public void setPlayer(SlimPlayer player) {
        this.player = player;
    }

    /**
     * @return the playlist
     */
    public SlimPlaylist getPlaylist() {
        return playlist;
    }

    /**
     * @param playlist the playlist to set
     */
    public void setPlaylist(SlimPlaylist playlist) {
        this.playlist = playlist;
    }

    /**
     * @return the startTime
     */
    public int getStartTime() {
        return startTime;
    }

    /**
     * @param startTime the startTime to set
     */
    public void setStartTime(int startTime) {
        this.startTime = startTime;
    }

    /**
     * @return the endTime
     */
    public int getEndTime() {
        return endTime;
    }

    /**
     * @param endTime the endTime to set
     */
    public void setEndTime(int endTime) {
        this.endTime = endTime;
    }

    public int getDelay() {
        try {
            return Integer.parseInt(tfDelay.getText().trim());
        } catch (Exception e) {
            return 5;
        }
    }

    private class LoopingThread implements Runnable {
        @Override
        public void run() {
            while (isLooping()) {
                try {
                    if (getPlayer().getElapsedTime() >= getEndTime()) {
                        if (!countDownThreadRunning) {
                            countDownThreadRunning = true;
                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    try {
                                        getPlayer().pause();
                                    } catch (SlimConnectionException ex) {
                                        Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    btnLoop.setVisible(false);
                                    lblCountDown.setText(Integer.toString(getDelay()));
                                    lblCountDown.setVisible(true);
                                    for (int i = getDelay(); i > 0; i--) {
                                        lblCountDown.setText(Integer.toString(i));
                                        try {
                                            Thread.sleep(1000);
                                        } catch (InterruptedException ex) {
                                            Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
                                        }
                                    }
                                    lblCountDown.setVisible(false);
                                    btnLoop.setVisible(true);
                                    try {
                                        getPlayer().seek(getStartTime());
                                    } catch (SlimConnectionException ex) {
                                        Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    try {
                                        getPlayer().play();
                                    } catch (SlimConnectionException ex) {
                                        Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    countDownThreadRunning = false;
                                }
                            }).start();
                        }
                    } else {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                } catch (SlimConnectionException ex) {
                    Logger.getLogger(GuitarPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private class TrackThread implements Runnable {

        private boolean stopped;

        public TrackThread() {
            try {
                time = player.getElapsedTime();
            } catch (SlimConnectionException ex) {
                Logger.getLogger(PlayerPanelThin.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        public void run() {
            int checkCount = 0;
            while (!isStopped()) {
                setElapsedTrackTime(getTime() + checkCount++);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(PlayerPanelThin.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (checkCount % 10 == 0) {
                    checkCount = 0;
                    try {
                        setTime(player.getElapsedTime());
                    } catch (SlimConnectionException ex) {
                        Logger.getLogger(PlayerPanelThin.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }

        /**
         * @return the stopped
         */
        public boolean isStopped() {
            return stopped;
        }

        /**
         * @param stopped the stopped to set
         */
        public void setStopped(boolean stopped) {
            this.stopped = stopped;
        }
    }

    /**
     * @return the time
     */
    public int getTime() {
        return time;
    }

    /**
     * @param time the time to set
     */
    public void setTime(int time) {
        this.time = time;
    }
}
